//
//  HomeViewController.swift
//  CellAutolayoutHeight
//
//  Created by zk_01 on 2022/3/29.
//

import UIKit
import Foundation
import SnapKit
import Kingfisher

class HomeViewController: UIViewController {
    
    var dataSourece = [DataModel]()
    
    var istream: InputStream?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        if self.dataSourece.isEmpty {
            self.dataSourece = DataPrepare.shared.loadData()
        }
        self.setupView()
//        NSString *path = [[NSBundle mainBundle] pathForResource:@"小食光光" ofType:@"mp4"];
        
//        self.setUpStreamForFile(Bundle.main.path(forResource: "小食光光", ofType: "mp4")!)
    }
    
    func setupView(){
        self.navigationController?.viewControllers = [self]
        self.navigationController?.navigationBar.isTranslucent = false
        self.navigationController?.navigationBar.backgroundColor = .orange
        
        //ios 15系统
        if #available(iOS 15.0, *) {
            let appperance = UINavigationBarAppearance()
            appperance.backgroundColor = .orange
            appperance.shadowImage = UIImage()
            appperance.shadowColor = nil
            self.navigationController?.navigationBar.standardAppearance = appperance
            self.navigationController?.navigationBar.scrollEdgeAppearance = appperance
        }
        
        
        self.tableView.snp.makeConstraints { make in
            make.edges.equalTo(self.view)
        }
    }
    
    lazy var tableView: UITableView = {
        let tableView = UITableView(frame: CGRect.zero, style: .plain)
        tableView.dataSource = self
        tableView.delegate = self
        tableView.register(TextCell.self,  forCellReuseIdentifier:  CellType.text.rawValue)
        tableView.register(ImageCell.self, forCellReuseIdentifier:  CellType.image.rawValue)
        self.view.addSubview(tableView)
        return tableView
    }()
}

extension HomeViewController:UITableViewDelegate,UITableViewDataSource{
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.dataSourece.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let model = self.dataSourece[indexPath.row]
        let cell = tableView.dequeueReusableCell(withIdentifier: model.cellType.rawValue, for: indexPath)
        (cell as! BaseCell).setModel(model)
        return cell
    }
    
    func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        /**⚠️⚠️⚠️  在使用 UITableView.automaticDimension 时，对于需要动态高度的子控件(比如:动态高度Lab，textView等)，不能在这里赋值，在这里赋值无法实现自适应高度  ⚠️⚠️⚠️**/
        //        (cell as! BaseCell).setModel(model)
        
        let model = self.dataSourece[indexPath.row]
        model.cellHeight = cell.frame.height
        (cell as! BaseCell).events = { [weak self] cell,model,el in
            switch el{
            case .void:
                
                break
            case .contentCollapse(_):
                
                break
            }
            
            self?.tableView.reloadData()
            //            self?.tableView.reloadRows(at: [indexPath], with: UITableView.RowAnimation.none)//收起的效果不好
        }
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
    }
    
    func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
        
        let model = self.dataSourece[indexPath.row]
        if model.cellHeight > 0.0 {
            return model.cellHeight
        }
        return 150
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        
        return UITableView.automaticDimension
    }
}

extension HomeViewController:StreamDelegate{
    func setUpStreamForFile(_ path:String){
        print("111RunLoop.current = \(RunLoop.current)")
        DispatchQueue.init(label: "dd").async {
            
            self.istream = InputStream(fileAtPath: path)
            self.istream?.delegate = self
            self.istream?.schedule(in: RunLoop.current, forMode: .common)
            print("222RunLoop.current = \(RunLoop.current)")

            self.istream?.open()
            RunLoop.current.run()

        }
    }
    
    func stream(_ aStream: Stream, handle eventCode: Stream.Event){
        
        switch eventCode{
        case .openCompleted: //流对象被成功打开
            print("流对象被成功打开")
        case .hasBytesAvailable: //流对象有数据可读 (NSSInputStream)
            let maxLength = 100
            let buf = UnsafeMutablePointer<UInt8>.allocate(capacity: maxLength)
            self.istream!.read(buf, maxLength: maxLength)
            buf.deallocate()
            buf.deinitialize(count: maxLength)
            
        case .hasSpaceAvailable: //还有空间提供给流对象写入缓冲区 (NSOuputStream)
            break
        case .endEncountered: //流对象完成数据读取
            aStream.close()
            aStream.remove(from: RunLoop.current, forMode: .common)
        case .errorOccurred: //流对象读取数据错误
            print("流对象读取数据错误")
            break
        default:
            break
        }
    }
}

